<template>
  <base-window size="larger" :unique="false" class-name="agenda-event" :show.sync="dialogFormVisible" :title="title" @closed="reset">
    <div class="schedule-content">
      <div class="schedule-scroll-content">
        <el-form label-position="top" ref="formRef" :model="form" size="mini">
          <!-- 事件新建表单 -->
          <event-edit-view :plan-time-config="planTimeConfig" class="agenda-event-edit-view" :agenda-event="true" :plan-start-time="form.startTime" :plan-end-time="form.endTime" :event-type-list-init="eventTypeList" ref="agendaEventRef"/> 
        
        </el-form>
      </div>
      <div class="schedule-scroll-content">
        <div class="users-time">
          <div class="clash">
            <p class="clash-tip">
              <!-- <i v-if="clashCount" class="iconfont icon-jinggao"></i> 
              <i v-else class="iconfont icon-yitongguo"></i> 
              {{clashCount ? `${clashCount}人日程有冲突` : '暂无日程冲突'}} -->
            </p>  
            <div class="clash-right">
              <!-- <el-select v-model="clashType" placeholder="冲突类型" clearable>
                <el-option label="完全冲突" :value="1"></el-option>
                <el-option label="完全不冲突" :value="2"></el-option>
                <el-option label="部分冲突" :value="3"></el-option>
              </el-select> -->
              <el-select class="work-state"
                        v-model="statusList"
                        multiple
                        collapse-tags
                        :placeholder="$t('common.base.workState')">
                <el-option
                  v-for="item in userStateList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  <div class="schedule-work-state-item">
                    <span class="state-color-icon" :style="{backgroundColor: item.color}"></span>
                    <span>{{item.label}}</span>
                  </div>
                </el-option>
              </el-select>
              <el-button class="bnt-add-user" @click="selectApproveUser" type="primary" plain icon="el-icon-plus" size="mini">{{$t('calendar.detail.addPeople')}}</el-button>
            </div>
          </div>

          <p v-if="GanttData.length > 0" class="users-time-tips">{{$t('calendar.detail.oprateText')}}</p>
          
          <div v-if="form.endTime" class="container">
            <gantt-chart
              :gantt-data="GanttData"
              :time-section="GanttTime"
              :chart-max-height="ChartHeight"
              type="event"/>
          </div> 
  
        </div> 
      </div>

    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">{{$t('common.base.close')}}</el-button>
      <el-button type="primary" @click="submit">{{$t('common.base.save')}}</el-button>
    </div>

    <div class='task-allot-user-content agenda-user-card'>
      <base-panel width='470px' :show.sync="showUserCard">
        <user-card
          :state-color-map="stateColorMap"
          :task="{}"
          :show-synergy-button="true"
          :user-id="excutorUserId"
          @close="showUserCard=false" 
          @setExecutor="setExecutor"
          @setSynergy="setSynergy"/>
      </base-panel>
    </div>

  </base-window >

</template>

<script>

import UserCard from '@src/modules/task/components/TaskAllotModal/UserCard/UserCard.tsx'
import moment from 'moment'
import { getRootWindow } from '@src/util/dom'
import { getStateColorMap } from '@src/api/SettingApi'
import * as CalendarApi from '@src/api/CalendarApi.ts'
import _ from 'lodash';
import { safeNewDate } from '@src/util/time';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { getTimestamp } from 'pub-bbx-utils';
export default {
  name: 'agendar-event-dailog',
  inject:['initData'],
  props: {
    eventStartTime: {
      type: String,
      default: ''
    },
    eventEndTime: {
      type: String,
      default: ''
    },
    agendaInfo: {
      type: Object,
      default: ()=>({})
    },
    planTimeConfig: {
      type: Number,
      default: 30
    }
  },
  components: {
    UserCard
  },
  data() {
    return {
      showUserCard: false,
      excutorUserId: '',
      stateColorMap: {},

      dialogFormVisible: false,
      title: this.$t('calendar.detail.createEventAgenda'), 
      form: {
        name: '',
        type: 1,
        startTime: '',
        endTime: '',
        descr: '',
        isRepeat: 0,
        repeatType: '0',
        acceptNotice: 0,
        refuseNotice: 0,
        noticeType: 1,
        noticeContent: '',
        minutes: '0',
        users:[]
      },
      clashType: '',
      statusList:[],
      userStateList: [],
      clashCount: 0,

      GanttData: [],
      GanttCurrentTime: safeNewDate().getTime(),
      // 定时器
      marker: null,
      ChartWidth: 80,
      ChartHeight: 600,
    }
  },
  computed: {
    eventTypeList(){
      return this.initData.eventTypeList 
    },
    loginUser(){
      return this.initData.loginUser 
    },
    selectUsers(){
      return this.form.users
    },
    GanttTime(){
      // 时间轴以计划开始时间和完成时间  
      return [moment(this.form.startTime).format('YYYY/MM/DD HH:mm'), moment(this.form.endTime).format('YYYY/MM/DD HH:mm')]
    },
  },
  watch: {
    eventStartTime: {
      immediate: true,
      handler() {
        // console.info('selectstartTime::', this.startTime);
        if(this.eventStartTime) {
          // 日程开始和结束时间
          this.form.startTime = this.eventStartTime
          this.form.endTime = this.eventEndTime
          this.getClashUserTime() 
        }
      }
    },
    agendaInfo: {
      immediate: true,
      deep: true,
      handler() {
        // console.info('this.agendaInfo::', this.agendaInfo);
        if(this.agendaInfo.id) {
          const type = this.agendaInfo.type;
          this.title = type == 3 ? this.$t('calendar.detail.editcommonAgenda') : (type == 1 ? this.$t('calendar.detail.editEventAgenda') : this.$t('calendar.detail.editTaskAgenda'))
          this.getAgendaInfo(this.agendaInfo.id)
        }
      }
    },
    selectUsers: {
      deep: true,
      handler() {
        this.getClashUserTime() 
      }
    },
    clashType:{
      handler() {
        this.getClashUserTime() 
      }
    },
    statusList:{
      handler() {
        this.getClashUserTime() 
      }
    },
  },
  mounted () {
    this.$eventBus.$on('agenda-event-user-card', this.handleUserCard)
    this.$eventBus.$on('agendar-create-event', this.handleCloseSelf)
    this.$eventBus.$on('agendar-event-select-executor', this.handleSelectExecutor)
    this.$eventBus.$on('agendar-event-select-synergies', this.handleSelectSynergies)
    this.$eventBus.$on('agenda-event-plan-start-time', this.handleStartTime)
    this.$eventBus.$on('agenda-event-plan-end-time', this.handleEndTime)
    // this.marker = setInterval(() => {
    //   this.GanttCurrentTime += 1000
    // }, 1000) 
    // this.form.users.push(this.loginUser);
    // 初始化工作状态和颜色
    this.initWorkState()
  },
  methods: {
    reset(){
      this.title = this.$t('calendar.detail.createEventAgenda')
      this.form.startTime = this.startTime
      this.form.endTime = this.endTime
      this.form.users = []
      this.GanttData = []
      this.clashCount = 0
      this.clashType = ''
      this.statusList = []
    },
    handleStartTime(e){
      this.form.startTime = e
      this.getClashUserTime() 
    }, 
    handleEndTime(e){
      this.form.endTime = e
      this.getClashUserTime() 
    }, 
    handleUserCard(event){
      this.excutorUserId = event.userId
      this.showUserCard = true
    },
    // user-card 设置负责人
    setExecutor(user){
      this.$eventBus.$emit('agenda-event-executor', user)
    },
    setSynergy(user) {
      this.$eventBus.$emit('agenda-event-synergy', user)
    },
    getClashUserTime(){
      if(this.form.startTime && this.form.endTime && this.form.users.length) {
        this.getAgendaUsersTime()
        // this.getAgendaUsersTimeNum()
      } else {
        this.GanttData = []
      }
    },
    initWorkState(){
      getStateColorMap().then(res => {
        this.stateColorMap = res || {}
        let list = []
        let userStateMap = {}
        try {
          let rootWindow = getRootWindow(window)
          let initData = JSON.parse(rootWindow?._init || '{}')
          userStateMap = initData.userStateMap
        } catch (error) {
          userStateMap = {}
          console.error('error', error)
        }
        for (let userStateKey in userStateMap) {
          let userState = {
            key: userStateKey,
            value: userStateKey,
            label: userStateKey,
            color: res[userStateKey]
          }
          list.push(userState)
        }
        this.userStateList = list
      })
    },
    async getAgendaUsersTime(){
      if(!this.form.users.length) return
      try {
        const params = {};
        params.startTime = this.form.startTime
        params.endTime = this.form.endTime
        params.userIds = this.form.users.map(item=>item.userId)
        params.clashType = this.clashType ? this.clashType : 0
        params.statusList = this.statusList
        const res = await CalendarApi.getAgendaUsersTime(params);
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.GanttData = res.data?.list || []
      } catch (err) {
        console.error('err', err);
      }
    },
    async getAgendaUsersTimeNum(){
      if(!this.form.users.length) return
      try {
        const params = {};
        params.startTime = this.form.startTime
        params.endTime = this.form.endTime
        params.userIds = this.form.users.map(item=>item.userId)
        params.clashType = this.clashType
        params.statusList = this.statusList
        const res = await CalendarApi.getAgendaUsersTimeNum(params);
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.clashCount = res.data || 0
      } catch (err) {
        console.error('err', err);
      }
    },
    show() {
      this.dialogFormVisible = true
    },
    handleClose(user) {
      this.form.users.splice(this.form.users.indexOf(user), 1);
    },
    selectApproveUser(){
      let selected = _.cloneDeep(this.form.users)
      let obj = {};
      selected = selected.reduce((cur, next) => {
        obj[next.userId] ? '' : obj[next.userId] = true && cur.push(next);
        return cur;
      }, [])
      let options = {
        title: this.$t('calendar.detail.addPeople'), // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selected, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        unique: false,
        haveRole: true,
        mode: BaseSelectUserModeEnum.Filter
      }
      
      this.$fast.select.multi.user(options)
        .then((res) => {
          if (res.status != 0 || !res.data) return
          let list = res.data.users || []
          // list = list.filter(item=>item.userId != this.loginUser.userId) 
          // this.form.users = [...this.form.users, ...list] ;
          this.form.users = list
          // this.$eventBus.$emit('agenda-event-synergy', list)
        })
        .catch((err) => {
          console.warn(err)
        })
    },
    handleCloseSelf(){
      this.dialogFormVisible = false
      this.$emit('submitCreateEvent');
    },
    handleSelectExecutor(user){
      const list = this.form.users.filter(item=>item.userId != user.userId)
      this.form.users = [...list, user]
    }, 
    handleSelectSynergies(users){
      // const list = users.filter(item=>item.userId != this.loginUser.userId)
      let old = this.form.users
      this.form.users = [...old, ...users]
    },
    submit() {
      this.form.startTime = getTimestamp(this.form.startTime)
      this.form.endTime = getTimestamp(this.form.endTime)
      if(safeNewDate(this.form.startTime).getTime() > safeNewDate(this.form.endTime).getTime()) {
        return this.$platform.notification({
          title: this.$t('calendar.limit.timeLimit'),
          type: 'error'
        });
      }
      if(safeNewDate(this.form.startTime).getTime() < safeNewDate().getTime()) {
        return this.$platform.notification({
          title: this.$t('common.modal.PLAN_START_TIME_NOT_LESS_THEN_NOW_MEESSAGE'),
          type: 'error'
        });
      }
      const params = {}
      params.planStartTime = this.form.startTime
      params.planEndTime = this.form.endTime
      this.$refs.agendaEventRef.handleSave(params)
    },
    // 获取日程详情
    async getAgendaInfo(agendaId){
      try {
        let res = await CalendarApi.getAgendaCalendarInfo({agendaId});
        if(res.status != 0) {
          return this.$platform.notification({
            title: res.message,
            type: 'error'
          });
        }
        this.form = res.data.agendaInfo;
        this.form.startTime = this.agendaInfo.startTime
        this.form.endTime = this.agendaInfo.endTime
        this.form.minutes = String(this.form.minutes)
        this.form.repeatType = String(this.form.repeatType)
        this.form.users = res.data.users
      } catch (err) {
        console.error('err', err);
      }
    },
  }, 
  destroyed () {
    this.$eventBus.$off('agenda-event-user-card', this.handleUserCard)
    this.$eventBus.$off('agendar-create-event', this.handleCloseSelf)
    this.$eventBus.$off('agendar-event-select-synergies', this.handleSelectSynergies)
    this.$eventBus.$off('agenda-event-plan-start-time', this.handleStartTime)
    this.$eventBus.$off('agenda-event-plan-end-time', this.handleEndTime)
  },
}
</script>
<style lang="scss" scoped>
.schedule-content{
  display: flex;
  height: 100%;
  .schedule-scroll-content{
    height: 100%;
    overflow-y: auto;
    >.el-form{
      width: 100%;
      height: 100%;
    }
    >.users-time{
      width: 100%;
    }

    &:nth-child(1){
      flex: 1;
    }
    &:nth-child(2){
      flex: 1;
    }
  }
  .el-form {
    width: 50%;
    border-right: 1px solid #eee;
    .no-left {
      ::v-deep .el-form-item__content{
        margin-left: 0!important;
      }
    }
    .user-tag {
      background-color: #fff;
      background-image: none;
      border-radius: 2px;
      border: 1px solid #e0e1e2;
      padding-left: 10px;
      .el-tag--mini{
        margin-right: 10px;
      }
    }
    .noti-time{
      margin-right: 15px;
    } 
  }
  
  .users-time{
    width: 50%; 
    display: flex;
    flex-direction: column;
    .clash{
      display: flex;
      justify-content: space-around;
      height: 40px;
      line-height: 40px;
      padding: 0 10px;
      .clash-tip{
        min-width: 100px;
        .icon-yitongguo {
          color: #52C41A;
        }
        .icon-jinggao {
          color: #FF4D4F;
        }
      }
      .clash-right {
        flex: 1;
        display: flex;
        justify-content: flex-end;
      }
      .el-select{
        max-width: 150px;
        margin: 0 5px;
      }
      .work-state{
        max-width: 150px;
        ::v-deep .el-tag {
          display: flex;
          align-items: center;
          max-width: 65px;
          @include text-ellipsis();
          .el-select__tags-text {
            display: inline-block;
            max-width: 40px;
            @include text-ellipsis();
          }
          .el-tag__close.el-icon-close {
            right: -3px;
          }
        }
      }
      .bnt-add-user{
        padding: 0 15px;
        height: 32px;
        line-height: 32px;
        margin-top: 4px;
        border-radius: 4px;
        margin-left: 5px;
      }
    }
    .users-time-tips {
      padding: 0 10px;
      margin: 0;
      color: $color-warning;
    }
    .el-table {
      flex: 1;
      height: calc(100vh - 196px);
      ::v-deep .el-table_1_column_1  {
        border-bottom: none!important;
      }
      ::v-deep td .is-hidden > *{
        visibility: visible!important;
      }
    }
  }

  .schedule-work-state-item{
    display: flex;
    align-items: center;
    .state-color-icon{
      display: inline-block;
      border-radius: 50%;
      width: 10px;
      height: 10px;
      margin-right: 10px;
    }
  }

}
</style>

<style lang="scss">
.agenda-event {
  .layx-html {
    overflow-x: hidden!important;
    .base-window-content-body {
      overflow: hidden;
    }
  }
}

.agenda-event-edit-view {
  padding-right: 12px!important;
}
 
</style>